<template>
    <div class="classifyBox padB25">
        <div class="classifyList">
            <div class="filterList padTB40" v-for="(item,index) in shoppingList" :key="index">
                <!-- <img src="../../public/static/img/indexBg.jpg" mode="aspectFill" class="photo"> -->
                <image-com :src="baseURL + item.mainImageUrl" :imgStyle="{width: '4.25rem',height: '4.25rem'}"></image-com>
                <div class="marL40 filterItem">
                    <div class="font28 bold line15">{{item.productName}}</div>
                    <div class="font24 line15 itemspan" >{{ getPackageDetails(item) }}</div>
                    <div class="addSubtWrapper">
                        <div class="total bold font38">
                            &yen; {{singleItemCalculate(item)}}<!-- /{{item.unitName}} -->
                        </div>
                    </div>
                </div>
            </div>
            <div class="filterList padT40">
                <div class="totalBox font30">
                    <div class="line15" >总计：</div>
                    <div class="line15">&yen;{{sumPrice}}</div>
                </div>
            </div>
        </div>
        <div class="classifyList">
            <div class="remarkBox">
                <div class="font28">备注</div>
                <input class="remarkInput font28 color92" v-model="comment" placeholder="有忌口填这里"/>
            </div>
        </div>
        <div class="replaceBottomBox">
            <div class="marL40 w33 font48 colorP"><span class="font30">&yen;</span>{{sumPrice}}</div>
            <div class="btn cancelBtn" @click="back">继续点餐</div>
            <div class="btn surnBtn" @click="addOrder">下单并支付</div>
        </div>
        <!-- <serviceRang /> -->
    </div>
</template>
<script>
//import serviceRang from '@/components/common/serviceRang'
import {AddOrder,GetCartByTableId,getPayArgs} from '@/api/order'
import { mapState,mapGetters,mapMutations } from "vuex";
import _ from 'lodash'
import imageCom from "@/components/common/imageCom.vue";
import { baseURL } from "@/api/config";
import { singleItemCalculate } from "@/utils/cartFn";
import { Toast } from 'vant';
export default {
    name: 'toOrder',
    components:{
        //serviceRang
        imageCom
    },
    computed:{
        ...mapState({
            shoppingList: (state) => state.cartModule.shoppingList
        }),
        ...mapGetters({
            mapShoppingList: 'mapShoppingList',
        }),
        /**
         * @description 总价格
         */
        sumPrice() {
            let defaultPrice = 0;
            for (let item of this.mapShoppingList) {
                defaultPrice += this.singleItemCalculate(item);
            }
            return defaultPrice;
        },
    },
    data(){
        return{
            baseURL,
            comment:'',
            tableObject: []
        }
    },
    created(){
        //clearInterval(timer)
        this.reqGetCartByTableId()
        this.$store.state.timer = setInterval(()=>{
            //console.log(1)
            this.reqGetCartByTableId()
        },5000)
    },
    beforeDestroy() {
        clearInterval(this.$store.state.timer);
        this.$store.state.timer = null;
    },
    methods:{
        ...mapMutations([
            "increaseProCart",
            "decreaseProCart",
            "setShoppintList",
            "clearshoppingList",
            "modifyProNew",
        ]),
        singleItemCalculate,
        /**
		 * @description 套餐内容
		 */
		getPackageDetails(mapItem) {
			let { packages } = mapItem;
			let descArr = [];
			for (let p of packages) {
				if (p.qty > 0) {
					let unitName = p?.unit?.unitName ?? "";
					let desc = `${p.productName}x${p.qty}${unitName}`;
					descArr.push(desc);
				}
			}
			let detail = descArr.join("+");
			return detail;
		},
        /**
         * @description 订单详情
        */
        async reqGetCartByTableId() {
            let params={
                tableId: this.$store.state.tableInfo.tableId
            }
            let { returnData = false } = await GetCartByTableId(params);
            if (returnData == false) {
                this.setShoppintList({ list: [] });
                return;
            }
            this.users = returnData.users;
            this.tableObject = returnData.details;
            !_.isEqual(this.$store.state.cartModule.shoppingList,this.tableObject)&&this.setShoppintList({list:this.tableObject})
        },
        async addOrder(){
            this.reqGetCartByTableId()
            let param = {
                tableId: this.$store.state.tableInfo.tableId,
                peopleCount: this.$store.state.tableInfo.num,
                comment: this.comment,
                items: this.handleItems(this.$store.state.cartModule.shoppingList)
            }
            //console.log(param)
            let { returnCode,returnData, isSuccess,message }  = await AddOrder(param)
            if(isSuccess == false) {
                Toast(message)
                return
            }
            if(returnCode!=0){
                Toast("下单失败")
            }else{
                this.orderId = returnData;
                this.pay()
                //this.$router.push({path:'/orderDetail',query:{orderId:returnData}})
            }
        },
        pay() {
            var that=this
            let params = {
                orderId: that.orderId
            }
            getPayArgs(params).then(function(result){
                debugger
                that.onBridgeReady(result.returnData)
            },function(result){
                debugger
                Toast(result.message);
            })
        },
        onBridgeReady(params) {
            var that = this
            WeixinJSBridge.invoke(
                'getBrandWCPayRequest', {
                    "appId": params.appId, //公众号名称，由商户传入
                    "timeStamp": params.timeStamp, //支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
                    "nonceStr": params.nonceStr, //支付签名随机串，不长于 32 位
                    "package": params.package, //统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
                    "signType": 'MD5', //签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
                    "paySign": params.paySign, //支付签名
                },
                function(res) {
                    if (res.err_msg === "get_brand_wcpay_request:ok") {
                        Toast('支付成功！');
                        that.$router.replace({
                            path:'/orderDetail',
                            query:{orderId: that.orderId}
                        })
                    } else if (res.err_msg === "get_brand_wcpay_request:fail") {
                        Toast('支付失败！');
                    }
                });
        },
        handleItems(list){
            let newList = []
            list?.forEach(val => {
                // if(val.packages){
                //     val['items'] =  val.packages
                //     delete val.packages
                // }
                newList.push(this.testHander(val))
            });
            return newList
        },
        testHander(item, isPackage = false){
            // if (isPackage == true) {
            //     let res = item.qty > 0 ? true : false;
            //     if (res == false) return res;
            // }
            // let unitId = "";
            // if (item.type == 3 || item.type == 5) {
            //   unitId = isPackage == false ? item.baseUnit.unitId : item.unit.unitId;
            // } else {
            //  unitId = item.baseUnitId ?? "";
            // }
            //let qty = isPackage == true ? item.itemCount : item.qty;
            let obj = {
                productId: item.productId,
                unitId:"",
                type: item.type,
                qty: item.qty ?? 0,
                state: item.type,
                configIds: [],
                items: [],
                comment: "",
                detailId:""
            };
            // 备注
            if (item.comment) {
                obj.comment = item.comment;
            }
            // detailId
            if (item.detailId) {
                obj.detailId = item.detailId;
            }
            if (item.type == 3 && isPackage == false) {
                for (let pitem of item.packages) {
                    let res = this.testHander(pitem, true);
                    if (res != false) {
                        obj.items.push(res);
                    }
                }
            } else if (item.type == 5) {
                console.log(item)
                for (let fitem of item.foodGroups) {
                    console.log(fitem)
                    obj.configIds.push(fitem.configId);
                }
            } else if (item.type == 0 && item?.sku?.length > 0) {
                console.log(item)
                for (let sitem of item.sku) {
                if (sitem.isDefault == true) {
                    obj.configIds.push(sitem.skuId);
                }
                }
            }
            return obj;
            },
        back(){
            this.$router.go(-1)
        }
    }
}
</script>
<style lang="scss" scoped>
    .classifyBox{
        .classifyList{ margin: 5.3%; padding: 5.3%; background-color: #fff; border-radius: 0.3rem; box-sizing: border-box;
            .filterList{ position: relative; display: flex; display: -webkit-flex; flex-wrap: wrap; -webkit-flex-wrap: wrap;  align-content: flex-start; -webkit-align-content: flex-start;
                .photo{ display: block; text-align: center; overflow: hidden; width: 4.25rem;  height: 4.25rem; border-radius: 0.3rem;}
                .filterItem{ flex: 1; display: flex; flex-direction: column; justify-content: space-between;
                .itemspan{ overflow: hidden; text-overflow: ellipsis; display: -webkit-box; -webkit-line-clamp: 2;-webkit-box-orient: vertical;
                    .num{ background-color: #ffeca9; color: #feb329; border-radius: 5px;padding: 0 0.25rem; margin-right: 0.25rem;}
                }
                }
                &:first-child{ padding-top: 0;}
                &+.filterList:after{content: " "; position: absolute; left: 0.4rem; top: 0; right: 0.4rem; height: 1px; border-top: 1px solid #E5E5E5; color: #E5E5E5; -webkit-transform-origin: 0 0; transform-origin: 0 0; -webkit-transform: scaleY(0.5); transform: scaleY(0.5);}
            }
            .totalBox{ flex: 1; display: flex; display: -webkit-flex; align-items: center; -webkit-align-items: center; justify-content: flex-end; -webkit-justify-content: flex-end; }
            .remarkBox{ display: flex; display: -webkit-flex; align-items: center; -webkit-align-items: center; justify-content: space-between; -webkit-justify-content: space-between;
                .remarkInput{
                    flex: 1; text-align: right; background: transparent; border: none; outline: none; color: #929292; line-height: normal;
                    &::-webkit-input-placeholder{ color: #929292;}
                }
            }
        }
        .replaceBottomBox{ position: fixed; left: 0; right: 0; bottom: 0; display: flex; justify-content: space-between; align-items: center; height: 2.75rem; line-height: 2.75rem; overflow: hidden; font-size: 0.7rem; background-color: #fff;
            .btn{ height: 2rem; line-height: 2rem; border-radius: 0.5rem; margin: 0 0.75rem;}
            .cancelBtn{ flex: 1; text-align: center; color: #333; margin-right: 0.375rem; border: 1px solid #333;}
            .surnBtn{ flex: 1; text-align: center; color: #333; margin-left: 0.375rem; background-image: linear-gradient(to right,$mainColor,#ffae44);}
        }
    }
</style>